import React, { useEffect, useState } from "react";
import { Button, Col, Form, Input, Flex, Row, Drawer, message, Select, Tabs, Checkbox } from "antd";
import { DeleteOutlined } from '@ant-design/icons';
import { apiSysDictSelect } from '../../../../services/common';
import { apiMSDItemSelect, apiMSDTempAdd, apiMSDTempView, apiMSDTempEdit } from '../../../../services/masterData/template';
import { transformArray } from '../../../../utils/commonUtil';
import { useTranslation } from 'react-i18next';
import {
  SYSCODE,
  DROPDOWN,
  TEXTINPUT,
  NUMBERINPUT,
  TEXTAREA,
  DATEPICKER,
  ATTACHMENT
} from '../../../../utils/constant';
import { getUserName } from '../../../../utils/commonUtil';
import { values } from "lodash";


const NewModal = (props) => {

  const [form] = Form.useForm();
  const { t } = useTranslation();
  const { TextArea } = Input;
  const username = getUserName();
  const [initialValues, setInitialValues] = useState();
  const [sysDictData, setSysDictData] = useState({});
  const [dropdownNameList, setDropdownNameList] = useState({});

  const [textInputNameList, setTextInputNameList] = useState({});
  const [numberInputNameList, setNumberInputNameList] = useState({});
  const [textAreaNameList, setTextAreaNameList] = useState({});
  const [datepickerNameList, setDatepickerNameList] = useState({});
  const [attchmentNameList, setAttchmentNameList] = useState({});
  const [dropdownItemName, setDropdownItemName] = useState([]);


  const {
    openDrawer,
    setOpenDrawer,
    editSucessFn,
    editType,
    recordData } = props;

  const apiSysDictSelectAynsc = () => {
    const params = {
      sysCode: SYSCODE,
      dictCodes: ['md_item_type', 'bu', 'module']
    }
    apiSysDictSelect(params).then((res) => {
      if (res?.data) {
        setSysDictData(res?.data?.data);
      }
    });
  };

  const initModalData = (viewData) => {
    const a = viewData.templateFiledDtos;
    const transformedData = a?.reduce((acc, curr) => {
      if (!acc[curr.subCategoryCode]) {
        acc[curr.subCategoryCode] = [];
      }
      acc[curr.subCategoryCode].push(curr);
      return acc;
    }, {});
    const modalData = { ...viewData, ...transformedData };
    setInitialValues(modalData);

    // 获取到itemtype 发送获取itemname、itemvalue的api
    const filedTypes = Array.from(new Set(a.map(item => item.filedType)));
    filedTypes?.forEach((item) => {
      onChangeItemType(item)
    })

  };

  const apiMSDTempViewAynsc = () => {
    const params = {
      id: recordData.configDynamicTemplateId
    }
    apiMSDTempView(params).then((res) => {
      if (res?.data) {
        const viewData = res?.data?.data?.item;
        initModalData(viewData);
      }
    })
  }

  // new
  const apiMSDTempAddAynsc = (values, status) => {
    const templateFiledResult = [...values?.Project, ...values?.Product];
    const params = {
      buType: values.buType,
      moduleName: values.moduleName,
      status: status,
      templateName: values.templateName,
      templateFiledDtos: templateFiledResult,
      userId: username,
    };
    apiMSDTempAdd(params).then((res) => {
      if (res?.data) {
        setOpenDrawer(false);
        editSucessFn();
      }
    })
  }

  // edit
  const apiMSDTempEditAynsc = (values, status) => {
    const templateFiledResult = [...values?.Project, ...values?.Product];
    const params = {
      configDynamicTemplateId: recordData.configDynamicTemplateId,
      buType: values.buType,
      moduleName: values.moduleName,
      status: status,
      templateName: values.templateName?.trim(),
      templateFiledDtos: templateFiledResult,
      userId: username
    };
    apiMSDTempEdit(params).then((res) => {
      if (res?.data) {
        setOpenDrawer(false);
        editSucessFn();
      }
    })
  }

  const clickOKBtn = (status) => {
    const params = form?.getFieldsValue();
    form.validateFields().then(() => {
      if (editType === 'new') {
        apiMSDTempAddAynsc(params, status);
      } else if (editType === 'edit') {
        apiMSDTempEditAynsc(params, status);
      }
    }, () => {
      return false;
    });
  }

  const onChangeItemType = (value, name, index) => {
    console.log(value, name, index);
    const formData = form.getFieldsValue();
    const params = {
      buType: formData.buType,
      itemType: value,
      moduleName: formData?.moduleName
    };

    apiMSDItemSelect(params).then((res) => {
      if (res?.data) {
        if (value === DROPDOWN) {
          setDropdownNameList(res?.data?.data);
        } else if (value === TEXTINPUT) {
          setTextInputNameList(res?.data?.data);
        } else if (value === NUMBERINPUT) {
          setNumberInputNameList(res?.data?.data);
        } else if (value === TEXTAREA) {
          setTextAreaNameList(res?.data?.data);
        } else if (value === DATEPICKER) {
          setDatepickerNameList(res?.data?.data);
        } else if (value === ATTACHMENT) {
          setAttchmentNameList(res?.data?.data);
        }
      }
    });
    //
    if (name && formData && formData?.[name]) {
      let formDataTabItem = formData?.[name];
      formDataTabItem[index].filedName = [];
      formDataTabItem[index].filedValues = [];
      formData[name] = formDataTabItem;
      setInitialValues(formData);
    }
  }
  const getItemValueOptionFn = (filedType, filedName) => {
    let getFiledValue = [];
    if (filedType === DROPDOWN) {
      getFiledValue = dropdownNameList?.itemValues;
    }
    // else if (filedType === TEXTINPUT) {
    //   getFiledValue = textInputNameList?.itemValues;
    // } else if (filedType === NUMBERINPUT) {
    //   getFiledValue = numberInputNameList?.itemValues;
    // } else if (filedType === TEXTAREA) {
    //   getFiledValue = textAreaNameList?.itemValues;
    // }

    for (let i = 0; i < getFiledValue?.length; i++) {
      if (getFiledValue[i].hasOwnProperty(filedName)) {
        return getFiledValue[i][filedName];
      }
    }
  }

  const getItemNameOptionFn = (type) => {
    let option = [];
    if (type === DROPDOWN) {
      option = dropdownNameList?.itemNames;
    } else if (type === TEXTINPUT) {
      option = textInputNameList?.itemNames;
    } else if (type === NUMBERINPUT) {
      option = numberInputNameList?.itemNames;
    } else if (type === TEXTAREA) {
      option = textAreaNameList?.itemNames;
    } else if (type === DATEPICKER) {
      option = datepickerNameList?.itemNames;
    } else if (type === ATTACHMENT) {
      option = attchmentNameList?.itemNames;
    }
    return transformArray(option);
  }

  const buSelectChange = () => {
    if (form.getFieldsValue().buType && form.getFieldsValue().moduleName) {
      form.setFieldValue('Project', [{ subCategoryCode: 'Project' }]);
      form.setFieldValue('Product', [{ subCategoryCode: 'Product' }]);
    }
  }

  const onChangeItemName = (val, name, index, type, filedName) => {
    const formData = form?.getFieldsValue();
    const seenFiledNames = new Set();
    const seenFiledTypes = new Set();
    const allList = [...formData?.Project, ...formData?.Product]
    let formDataTabItem = formData?.[name];
    console.log('formDataTabItem[index]', formDataTabItem[index])
    // 重复item校验，当前项如果重复会删除并显示提示语
    for (const obj of allList) {
      if (seenFiledTypes.has(obj.filedType) && seenFiledNames.has(obj.filedName)) {
        formData[name] = formDataTabItem.splice(index, 1);;
        setInitialValues(formData);
        message.warning(t('masterData.duplicatedWarning'))
        return false;
      } else {
        seenFiledTypes.add(obj.filedType);
        seenFiledNames.add(obj.filedName);
      }
    }

    if (type === TEXTINPUT || type === TEXTAREA || type === NUMBERINPUT) {
      formDataTabItem[index] = {
        ...formDataTabItem?.[index],
        filedValues: type === DROPDOWN ? [getItemValueOptionFn(type, filedName)] : ['']
      };
    } else {
      formDataTabItem[index].filedValues = [];
      formDataTabItem[index].filedName = val;
    };
    formDataTabItem[index].isRequired = '0';
    formData[name] = formDataTabItem;
    setInitialValues(formData);
  }
  const isRequiredChange = (e, name, index) => {
    const formData = form?.getFieldsValue();
    let formDataTabItem = formData?.[name];
    formDataTabItem[index].isRequired = e?.target?.checked === true ? '1' : '0';
    formData[name] = formDataTabItem;
    setInitialValues(formData);
  }

  const addModuleFn = (name) => {
    return (
      <Form.List name={name}>
        {(fields, { add, remove }) => (
          <div
            className="itemTableClass"
            style={{
              display: 'flex',
              rowGap: 10,
              flexDirection: 'column',
            }}
          >
            <div className="items-header">
              <span style={{ width: '21%' }}>{t('common.type')}</span>
              <span style={{ width: '21%' }}>{t('common.item')}</span>
              <span style={{ width: '42%' }}>{t('common.itemValue')}</span>
              <span style={{ width: '10%' }}>{t('common.required')}</span>
            </div>
            {fields.map((field, index) => {
              return (
                <Flex>
                  <Form.Item label="" style={{ flex: 1, marginRight: '10px' }} name={[field.name, 'filedType']} rules={[{ required: true, message: t('common.inputRequired') }]}>
                    <Select
                      placeholder={t('common.pleaseSelect')} onChange={(value) => {
                        onChangeItemType(value, name, index);
                      }}
                      options={transformArray(sysDictData.md_item_type)} allowClear />
                  </Form.Item>
                  <Form.Item label="" style={{ flex: 1, marginRight: '10px' }} name={[field.name, 'filedName']} rules={[{ required: true, message: t('common.inputRequired') }]}>
                    <Select
                      placeholder={t('common.pleaseSelect')}
                      onChange={(val) => { onChangeItemName(val, name, index, form?.getFieldsValue()?.[name]?.[index]?.filedType, form?.getFieldsValue()?.[name]?.[index]?.filedName) }}
                      options={getItemNameOptionFn(form?.getFieldsValue()?.[name]?.[index]?.filedType)} />
                  </Form.Item>
                  {/* dropdown */}
                  {form?.getFieldsValue()?.[name]?.[index]?.filedType === DROPDOWN && <Form.Item label="" style={{ flex: 2, marginRight: '10px' }} name={[field.name, 'filedValues']} rules={[{ required: true, message: t('common.inputRequired') }]}>
                    <Select
                      placeholder={form?.getFieldsValue()?.[name]?.[index]?.filedType === DROPDOWN ? t('common.pleaseSelect') : ''}
                      options={transformArray(getItemValueOptionFn(form?.getFieldsValue()?.[name]?.[index]?.filedType, form?.getFieldsValue()?.[name]?.[index]?.filedName)?.split(','))}
                      mode="multiple"
                    />
                  </Form.Item>}
                  {/* input */}
                  {(form?.getFieldsValue()?.[name]?.[index]?.filedType === TEXTINPUT
                    || form?.getFieldsValue()?.[name]?.[index]?.filedType === TEXTAREA
                    || form?.getFieldsValue()?.[name]?.[index]?.filedType === NUMBERINPUT
                    || form?.getFieldsValue()?.[name]?.[index]?.filedType === DATEPICKER
                    || form?.getFieldsValue()?.[name]?.[index]?.filedType === ATTACHMENT)
                    && <Form.Item
                      label=""
                      rules={[
                        {
                          required:
                            form?.getFieldsValue()?.[name]?.[index]?.filedType === DROPDOWN,
                          message: t('common.inputRequired')
                        }]}
                      style={{ flex: 2, marginRight: '10px' }} name={[field.name, 'filedValues']}>
                      <Input
                        // disabled={form?.getFieldsValue()?.[name]?.[index]?.filedType === DATEPICKER || form?.getFieldsValue()?.[name]?.[index]?.filedType === ATTACHMENT}
                        disabled={true}
                        type={form?.getFieldsValue()?.[name]?.[index]?.filedType === NUMBERINPUT && 'number'} />
                    </Form.Item>}
                  <Form.Item label="" style={{ width: '50px', marginRight: '0px' }} name={[field.name, 'isRequired']}>
                    <Checkbox
                      checked={form?.getFieldsValue()?.[name]?.[index]?.isRequired === '1' ? true : false} onChange={(e) => isRequiredChange(e, name, index)} />
                  </Form.Item>

                  <Form.Item label="" initialValue={name} name={[field.name, 'subCategoryCode']}></Form.Item>
                  <Button
                    type="link" style={{ color: '#333', padding: '0' }} onClick={() => { remove(field.name); }}>
                    <DeleteOutlined />
                  </Button>
                </Flex>
              )
            })}

            <Button type="primary" ghost style={{ width: "100px" }}
              onClick={() => { if (form.getFieldsValue().buType && form.getFieldsValue().moduleName) { add() } else { message.warning(t('masterData.buWaring')) } }} block>
              {t('common.add')}
            </Button>
          </div>
        )}
      </Form.List>
    )
  }

  const items = [
    {
      key: 'project',
      label: t('common.project'),
      forceRender: true,
      children: addModuleFn('Project')
    },
    {
      key: 'product',
      label: t('common.product'),
      forceRender: true,
      children: addModuleFn('Product')
    }
  ];

  useEffect(() => {
    apiSysDictSelectAynsc();
    if (editType !== 'new') {
      apiMSDTempViewAynsc();
    } else {
      setInitialValues({});
    }
  }, [])

  return (
    <Drawer
      title={t(`common.${editType}`)}
      width={760}
      footer={
        <Flex justify='flex-end'>
          <Button type="primary" ghost onClick={() => clickOKBtn('Draft')} disabled={editType === 'view'}>{t('common.saveAsDraft')}</Button>
          <Button type="primary" style={{ marginLeft: '16px' }} onClick={() => clickOKBtn('Published')} disabled={editType === 'view'}>{t('common.publish')}</Button>
        </Flex>

      }
      onClose={() => setOpenDrawer(false)}
      open={openDrawer}>
      {initialValues && <Form form={form} initialValues={initialValues} disabled={editType === 'view'} layout="vertical">
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item name="templateName" label={t('common.templateName')} rules={[
              {
                required: true,
                message: t('common.inputRequired'),
              }

            ]}>
              <Input disabled={editType === 'edit' || editType === 'view'} placeholder={t('common.pleaseEnter')} allowClear />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item name="buType" label={t('common.bu')} rules={[
              {
                required: true,
                message: t('common.inputRequired'),
              }

            ]}>
              <Select disabled={editType === 'edit' || editType === 'view'}
                onChange={buSelectChange}
                placeholder={t('common.pleaseSelect')}
                options={transformArray(sysDictData.bu)} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item name="moduleName" label={t('common.module')} rules={[
              {
                required: true,
                message: t('common.inputRequired'),
              }

            ]}>
              <Select disabled={editType === 'edit' || editType === 'view'}
                onChange={buSelectChange}
                placeholder={t('common.pleaseSelect')}
                options={transformArray(sysDictData.module)} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Tabs defaultActiveKey="1" items={items} />
          </Col>
        </Row>
      </Form>}
    </Drawer>
  )
};

export default NewModal;